<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="sysYouYouUser.userName">
        <el-input v-model="queryParams.sysYouYouUser.userName" placeholder="请输入用户名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="题库名称" prop="questionBank.name">
        <el-input v-model="queryParams.questionBank.name" placeholder="请输入题库名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option v-for="dict in dict.type.order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- 隐藏新增按钮 -->
      <el-col :span="1.5" style="display: none;">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['points:info:add']">新增</el-button>
      </el-col>
      <!-- 隐藏修改按钮 -->
      <el-col :span="1.5" style="display: none;">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['points:info:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['points:info:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['points:info:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单ID" align="center" prop="id" />
      <el-table-column label="用户名" align="center">
        <template slot-scope="scope">
          {{ getUserName(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="题库封面图" align="center" width="100">
        <template slot-scope="scope">
          <img v-if="getQuestionBankCover(scope.row)" :src="getQuestionBankCover(scope.row)" alt="题库封面" class="bank-cover" />
          <span v-else>无封面</span>
        </template>
      </el-table-column>
      <el-table-column label="题库名称" align="center">
        <template slot-scope="scope">
          {{ getQuestionBankName(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="订单金额" align="center" prop="amount" />
      <el-table-column label="使用积分" align="center" prop="points" />
      <el-table-column label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关闭时间" align="center" prop="closeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.closeTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- 隐藏修改按钮 -->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['points:info:edit']" style="display: none;">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['points:info:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="sysYouYouUser.userName">
          <el-input v-model="form.sysYouYouUser.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="题库名称" prop="questionBank.name">
          <el-input v-model="form.questionBank.name" placeholder="请输入题库名称" />
        </el-form-item>
        <el-form-item label="订单金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入订单金额" />
        </el-form-item>
        <el-form-item label="使用积分" prop="points">
          <el-input v-model="form.points" placeholder="请输入使用积分" />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.order_status" :key="dict.value"
              :label="dict.value">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker clearable v-model="form.createTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="关闭时间" prop="closeTime">
          <el-date-picker clearable v-model="form.closeTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择关闭时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfoWithUser, getInfo, delInfo, addInfo, updateInfo } from "@/api/points/info"

export default {
  name: "Info",
  dicts: ['order_status'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      infoList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sysYouYouUser: { userName: null },
        questionBank: { name: null },
        status: null,
      },
      form: {
        id: null,
        sysYouYouUser: { userName: '' },
        questionBank: { name: '' },
        amount: null,
        points: null,
        status: null,
        createTime: null,
        closeTime: null
      },
      rules: {
        'sysYouYouUser.userName': [{
          required: true,
          message: "用户名不能为空",
          trigger: "blur"
        }],
        'questionBank.name': [{
          required: true,
          message: "题库名称不能为空",
          trigger: "blur"
        }],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      console.log('查询参数:', this.queryParams);
      // 使用多表查询API获取包含关联数据的订单列表
      listInfoWithUser({
        ...this.queryParams,
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      }).then(response => {
        console.log('原始响应数据结构:', Object.keys(response));

        // 确保rows字段存在
        let rows = response.rows || response.list || (response.data ? response.data.list : []);
        this.total = response.total || (response.data ? response.data.total : 0);

        console.log('处理前的rows数据:', rows);

        // 直接使用原始数据，不进行额外处理，将在getter函数中处理关联属性
        this.infoList = rows;

        console.log('最终显示数据:', this.infoList);
        this.loading = false;
      }).catch(error => {
        console.error('获取订单列表失败:', error);
        console.log('错误详情:', error.response);
        this.$message.error('加载数据失败');
        this.loading = false;
      });
    },

    /** 获取用户名的辅助函数 - 尝试多种可能的属性路径 */
    getUserName(row) {
      if (!row) return '未关联用户';

      // 尝试多种可能的属性路径
      if (row.sysYouYouUser && row.sysYouYouUser.userName) {
        console.log('通过sysYouYouUser.userName获取用户名:', row.sysYouYouUser.userName);
        return row.sysYouYouUser.userName;
      }
      if (row.userName) {
        console.log('通过userName直接获取用户名:', row.userName);
        return row.userName;
      }
      if (row.user && row.user.userName) {
        console.log('通过user.userName获取用户名:', row.user.userName);
        return row.user.userName;
      }

      console.log('无法获取用户名，返回默认值');
      return '未关联用户';
    },

    /** 获取题库名称的辅助函数 - 尝试多种可能的属性路径 */
    getQuestionBankName(row) {
      if (!row) return '未关联题库';

      // 尝试多种可能的属性路径
      if (row.questionBank && row.questionBank.name) {
        console.log('通过questionBank.name获取题库名称:', row.questionBank.name);
        return row.questionBank.name;
      }
      if (row.questionBankName) {
        console.log('通过questionBankName直接获取题库名称:', row.questionBankName);
        return row.questionBankName;
      }
      if (row.bank && row.bank.name) {
        console.log('通过bank.name获取题库名称:', row.bank.name);
        return row.bank.name;
      }

      console.log('无法获取题库名称，返回默认值');
      return '未关联题库';
    },

    /** 获取题库封面图的辅助函数 - 尝试多种可能的属性路径 */
    getQuestionBankCover(row) {
      if (!row) return '';

      // 尝试多种可能的属性路径
      if (row.questionBank && row.questionBank.url) {
        console.log('通过questionBank.url获取题库封面图:', row.questionBank.url);
        return row.questionBank.url;
      }
      if (row.questionBankUrl) {
        console.log('通过questionBankUrl直接获取题库封面图:', row.questionBankUrl);
        return row.questionBankUrl;
      }
      if (row.bank && row.bank.url) {
        console.log('通过bank.url获取题库封面图:', row.bank.url);
        return row.bank.url;
      }

      console.log('无法获取题库封面图');
      return '';
    },

    cancel() {
      this.open = false;
      this.reset();
    },

    reset() {
      this.form = {
        id: null,
        sysYouYouUser: { userName: '' },
        questionBank: { name: '' },
        amount: null,
        points: null,
        status: null,
        createTime: null,
        closeTime: null
      };
      this.resetForm("form");
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        sysYouYouUser: { userName: null },
        questionBank: { name: null },
        status: null,
      };
      this.handleQuery();
    },

    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单管理";
    },

    handleUpdate(row) {
      this.reset();
      const id = row?.id || this.ids[0];
      if (!id) {
        this.$message.warning('请选择一条记录');
        return;
      }

      getInfo(id).then(response => {
        const data = response?.data || {};
        // 确保关联对象存在
        this.form = {
          ...data,
          sysYouYouUser: data.sysYouYouUser || { userName: '' },
          questionBank: data.questionBank || { name: '' }
        };
        this.open = true;
        this.title = "修改订单管理";
      }).catch(error => {
        console.error('获取详情失败:', error);
        this.$message.error('加载详情失败');
      });
    },

    // 禁用表单提交功能
    submitForm() {
      this.$message.warning('当前功能已禁用');
      return;
    },

    handleDelete(row) {
      const ids = row?.id || this.ids;
      if (!ids || (Array.isArray(ids) && ids.length === 0)) {
        this.$message.warning('请选择记录');
        return;
      }

      this.$modal.confirm(`是否确认删除订单编号为"${Array.isArray(ids) ? ids.join(',') : ids}"的数据？`).then(() => {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    handleExport() {
      this.download('points/info/export', { ...this.queryParams }, `info_${Date.now()}.xlsx`);
    }
  }
}
</script>

<style scoped>
  .bank-cover {
    width: 60px;
    height: 60px;
    object-fit: cover;
    border-radius: 4px;
    border: 1px solid #e6e6e6;
  }
</style>
